package controllers;

import java.lang.reflect.Type;
import java.util.Date;
import java.util.List;

import models.ConstructionProject;
import models.ProjectVisualize;
import models.ProjectVisualizeReport;
import models.Role;
import utils.YUtils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

public class ConstructionProjects extends Application {
	
	public static void index(){
		List<ProjectVisualize> pvs = ProjectVisualize.findAll();
		render(pvs);
	}
	
	public static void getJson(){
		List<ConstructionProject> cps  = ConstructionProject.findByDept(connectedUser().dept);
		String jsonStr = ConstructionProject.toJSON(cps);
		String json = YUtils.ligerGridData(jsonStr, cps.size());
		renderJSON(json);
	}
	
	/**
	 * add or modiry ConstruceionProject 
	 * @param consProject
	 * @param pvrInfo ProjectVisualizeReport 
	 * json info format :{ "projectVisuzlize":{"id":6},"quanlity":0,"accumulateComp":0}
	 */
	public static void add(ConstructionProject consProject,String pvrInfo){

        GsonBuilder builder = new GsonBuilder();   
        Gson gson = builder.create();   
		Type type = new TypeToken<List<ProjectVisualizeReport>>(){}.getType();
		
		if(consProject.id==null){
			consProject.belongDept = connectedUser().dept;
			consProject.noteUser = connectedUser();
		}else{
			if(consProject.verifyByHead()){
				renderText("不可修改");
			}
			consProject.modifyDate = new Date();
			consProject.modifyUser = connectedUser();
		}
		if(consProject.id!=null){
			ProjectVisualizeReport.delByConsPro(consProject);
		}
		consProject.save();
		if(!"".equals(pvrInfo) && pvrInfo!=null){
			List<ProjectVisualizeReport> pvrs = gson.fromJson(pvrInfo, type);
			for(ProjectVisualizeReport pvr: pvrs){
				pvr.consProject = consProject;
				pvr.save();
			}
		}
		ok();
	}
	
	public static void delete(long id){
		ConstructionProject cp = ConstructionProject.findById(id);
		if(cp.verifyByHead()){
			renderText("不可删除！");
		}
		ProjectVisualizeReport.delByConsPro(cp);
		cp.delete();
		ok();
	}
}